package com.loong.controller;

import com.loong.pojo.Cart;
import com.loong.pojo.User;
import com.loong.service.CartService;
import com.loong.service.impl.CartServiceImpl;
import com.loong.utils.Constants;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

@WebServlet("/cart")
public class CartController extends BaseServlet{

    public String create(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            session.setAttribute("msg", "请先登录");
            return Constants.REDIRECT + "/login.jsp";
        }
        int uid = user.getUid();
        int pid = Integer.parseInt(request.getParameter("pid"));
        CartService cartService = new CartServiceImpl();

        cartService.createCart(uid, pid);
        return Constants.FORWARD + "/cartSuccess.jsp";
    }

    public String show(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            session.setAttribute("msg", "请先登录");
            return Constants.REDIRECT + "/login.jsp";
        }
        Integer uid = user.getUid();
        CartService cartService = new CartServiceImpl();
        List<Cart> list = cartService.findAll(uid);
        request.setAttribute("list", list);

        return Constants.FORWARD + "/cart.jsp";
    }

    public String  delete(HttpServletRequest request, HttpServletResponse response){
        String cid = request.getParameter("cid");
        CartService cartService = new CartServiceImpl();
        cartService.deleteCartByCid(cid);
        return Constants.FORWARD + "/cart?method=show";
    }

    public String  update(HttpServletRequest request, HttpServletResponse response){
        String cid = request.getParameter("cid");
        String price = request.getParameter("price");//商品单价
        String cnum = request.getParameter("cnum");//修改后的数量
        CartService cartService = new CartServiceImpl();
        cartService.updateCartByCid(cid, price, cnum);
        return Constants.FORWARD + "/cart?method=show";
    }

    public String  clear(HttpServletRequest request, HttpServletResponse response){
        String uid = request.getParameter("uid");
        CartService cartService = new CartServiceImpl();
        cartService.clearCart(uid);
        return Constants.FORWARD + "/cart?method=show";
    }
}
